# -*- coding:utf-8 -*-
# 北梦测教育
# 课程咨询加微信：xiaobeiceshi
# 包含 钉钉消息，企微消息，邮件
# 面向对象的语法
import json
from dingtalkchatbot.chatbot import DingtalkChatbot
import zmail
import requests
import time
from utils.get_test_result_data import get_test_result_data
from utils.config_parser import GetConfig


class SendMessage:
    def __init__(self, env):
        # 判断环境获取地址
        report_link_dict = {
            "test": "report_link_test",
            "sting": "report_link_sting",
            "prod": "report_link_prod"
        }
        report_link = report_link_dict.get(env, "report_link_prod")

        # self.report_link = report_link_new
        self.get_config = GetConfig()
        self.report_link = self.get_config.get_message_report_path().get(report_link)
        self.now = time.strftime("%Y-%m-%d %H:%M:%S")
        # 获取钉钉消息配置
        self.config_dingding = self.get_config.get_message_dingding()

        # 获取企业微信消息配置
        self.config_wechat = self.get_config.get_message_wechat()

        # 获取邮箱配置
        self.config_email = self.get_config.get_message_email()

        # 从allure的json报告中获取测试结果
        self.result = get_test_result_data()
        self.passed = self.result.get("passed", 0)
        self.failed = self.result.get("failed", 0)
        self.skipped = self.result.get("skipped", 0)

    def send_message(self):
        raise NotImplementedError("发送消息的子类必须实现的方法")


class SendDingDingMessage(SendMessage):
    def send_message(self):
        # 接口测试报告
        # 1.名字：接口自动化测试报告
        # 2.测试时间是什么时间
        # 3.测试结果概述
        # 4.测试报告连接

        # ding = DingtalkChatbot(webhook, secret)
        ding = DingtalkChatbot(self.config_dingding.get("webhook"), self.config_dingding.get('secret'))
        ding.send_markdown("接口自动化测试报告", text=f"""
        **接口自动化测试概述**
- **测试时间**：{self.now}
- **测试结果**：
  - 成功：{self.passed}条
  - 失败：{self.failed}条
  - 跳过：{self.skipped}条
- **测试报告链接**：[点击访问]({self.report_link})
        """)


class SendMailMessage(SendMessage):
    def send_message(self):
        # mail = zmail.server(mail_username, mail_password)
        mail = zmail.server(self.config_email.get("mail_username"), self.config_email.get('mail_password'))
        mail.send_mail(
            recipients=self.config_email.get('recipients'),
            mail={
                "subject": "接口自动化通知",
                "content_html": f"""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>接口自动化测试报告</title>
    <style>
        body {{
            font-family: 'Segoe UI', system-ui, sans-serif;
            line-height: 1.6;
            max-width: 800px;
            margin: 2rem auto;
            padding: 0 20px;
            background-color: #f5f5f5;
        }}

        .report-card {{
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            padding: 2rem;
        }}

        h1 {{
            color: #2c3e50;
            border-bottom: 3px solid #3498db;
            padding-bottom: 0.5em;
            margin-bottom: 1.5rem;
            font-size: 2.2rem;
        }}

        .metadata {{
            margin-bottom: 1.5rem;
            color: #7f8c8d;
            font-size: 0.95rem;
        }}

        .result-stats {{
            display: flex;
            gap: 2rem;
            margin: 1.5rem 0;
        }}

        .stat-item {{
            flex: 1;
            text-align: center;
            padding: 1rem;
            border-radius: 8px;
        }}

        .success {{
            background: #e8f5e9;
            color: #2e7d32;
        }}

        .failure {{
            background: #ffebee;
            color: #c62828;
        }}

        a.report-link {{
            display: inline-block;
            padding: 0.8rem 1.5rem;
            background: #3498db;
            color: white !important;
            text-decoration: none;
            border-radius: 6px;
            transition: background 0.3s ease;
        }}

        a.report-link:hover {{
            background: #2980b9;
        }}
    </style>
</head>
<body>
    <article class="report-card">
        <header>
            <h1>接口自动化测试概述</h1>
            <div class="metadata">
                <strong>测试时间：</strong>{self.now}
            </div>
        </header>

        <section>
            <h2>测试结果</h2>
            <div class="result-stats">
                <div class="stat-item success">
                    <div style="font-size: 1.8rem; font-weight: bold;">{self.passed}</div>
                    <div>成功</div>
                </div>
                <div class="stat-item failure">
                    <div style="font-size: 1.8rem; font-weight: bold;">{self.failed}</div>
                    <div>失败</div>
                </div>
            </div>
        </section>

        <section style="margin-top: 2rem;">
            <a href="{self.report_link}" class="report-link">点击访问完整测试报告</a>
        </section>
    </article>
</body>
</html>
"""
            }
        )


class SendChatMessage(SendMessage):
    def send_message(self):
        data = {
            "msgtype": "markdown",
            "markdown": {
                "content": f"""
**接口自动化测试概述**
- **测试时间**：{self.now}
- **测试结果**：
  - 成功：{self.passed}条
  - 失败：{self.failed}条
  - 跳过：{self.skipped}条
- **测试报告链接**：[点击访问]({self.report_link})
        """
            }
        }
        requests.post(url=self.config_wechat.get('webhook'), headers=self.config_wechat.get('headers'),
                      data=json.dumps(data))


def send_message(env):
    """
    消息通知实际调用的函数
    :return:
    """
    message_object = [
        SendDingDingMessage(env),
        # SendChatMessage(env),
        SendMailMessage(env)
    ]
    # 现在老师是写了三个不同的对象来发送不同渠道的消息
    # 同学们实际工作中用几个，写几个，大部分情况应该就只有一种类型
    for mo in message_object:
        mo.send_message()


if __name__ == '__main__':
    send_message("test")
    # ding = SendDingDingMessage()
    # ding.send_message()
    # mail = SendMailMessage("https://www.sousou.com/")
    # mail.send_message()
    # chat = SendChatMessage("https://www.sousou.com/")
    # chat.send_message()
